package com.jl.runner;

import com.jl.ReflectUtils;
import com.jl.Tuple;
import com.jl.runner.annotation.Runner;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.List;

/**
 * 项目启动后执行任务
 */
@Slf4j
@Component
@AllArgsConstructor
public class CommandLineRunnerConfiguration implements CommandLineRunner {

    private ApplicationContext appContext;

    @Override
    @SneakyThrows
    public void run(String... args) {
        String[] beans = appContext.getBeanDefinitionNames();
        for (String bean : beans) {
            runner(appContext.getBean(bean));
        }
    }

    public void runner(Object bean) {
        Class<?> clazz = bean.getClass();
        List<Tuple.Tuple2<Method, Runner>> methods = ReflectUtils.MethodReflect.getMethod(clazz, Runner.class);
        methods.forEach(methodObj -> {
            Method method = methodObj.getV1();
            Runner jlRunner = methodObj.getV2();
            Object[] value = jlRunner.value();
            Object[] param = ReflectUtils.MethodReflect.checkParamType(method.getParameters(), value);
            try {
                method.invoke(bean, param);
            } catch (Exception e) {
                log.error("项目启动后执行任务失败：{}", e);
            }
        });
    }
}
